﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Crank.Core
{
    public class CalScripter : IScripter
    {
        #region IScripter Members

        public void Script(DataModel model, TextWriter output)
        {
            output.WriteLine("# Entities");
            ScriptEntities(model, output);
            output.WriteLine("# Links");
            ScriptLinks(model, output);
        }

        private void ScriptEntities(DataModel model, TextWriter output)
        {
            foreach (EntityDef entity in model.Entities.Values)
            {
                ScriptEntity(entity, output);
            }
        }

        private void ScriptEntity(EntityDef entity, TextWriter output)
        {
            output.WriteLine(entity.Name);
            foreach (AttributeDef att in entity.Attributes)
            {
                output.WriteLine("  <- {{ {0} }} {1}",
                    ToCal(att),
                    att.Type);
            }
            output.WriteLine();
        }

        private string ToCal(AttributeDef att)
        {
            return String.Format("{0}{1}{2}{3}",
                att.IsAuto ? "*" : "",
                att.IsKey ? "*" : "",
                att.Name.Length == 0 ? "_" : String.Format("[{0}]", att.Name),
                att.IsRequired ? "!" : "?");

        }

        private void ScriptLinks(DataModel model, TextWriter output)
        {
            foreach (LinkDef link in model.Links)
            {
                output.Write("{0} {1} {2} {3}",
                    link.LHS.Name,
                    link.Type,
                    String.Format("{{ {0} }}", ToCal(link.Detail)),
                    link.RHS.Name);
                output.WriteLine(" # {0}\n", Enumerables.Join(link.SourceColumns, ", "));
            }
        }

        #endregion
    }
}
